/* global chrome */
'use strict'
import RoomManage from './roommanage'
import RoomData from './roomdata'
export default class ServerProxy {
  constructor () {
    this.manage = new RoomManage()
    chrome.runtime.onConnect.addListener(this.onConnect.bind(this))
    chrome.runtime.onMessage.addListener(this.onceMessage.bind(this))
  }
  onConnect (port) {
    this.port = port
    RoomData.port = port
    this.port.disconnect = false
    this.port.onMessage.addListener(this.onMessage.bind(this))
    this.port.onDisconnect.addListener(this.onDisconnect.bind(this))
  }
  onDisconnect () {
    this.port.disconnect = true
  }
  onceMessage (message, sender, sendResponse) {
    let type = message.type
    let data = message.data
    switch (type) {
      case 'add':
        this.manage.addRoom(data.platform, data.roomId, (code, data) => {
          sendResponse({
            code,
            data})
          if (code === 0) {
            let key = data.platform.concat('_').concat(data.roomId)
            let obj = {
              avatar: data.info.avatar,
              roomName: data.info.roomName,
              roomId: data.info.roomId,
              nick: data.info.nick,
              platform: data.platform,
              date: this.getDate()
            }
            let value = {}
            value[key] = obj
            chrome.storage.sync.set(value)
          }
        })
        break
      case 'remove':
        this.manage.remove(data.platform, data.roomId)
        break
      case 'getRooms':
        sendResponse({
          rooms: this.manage.getRooms()
        })
        break
      case 'getRank':
        sendResponse({
          ranks: this.manage.getRank(data.key, data.field)
        })
        break
      case 'getGift':
        sendResponse({
          gifts: this.manage.getGift(data.key)
        })
        break
      case 'getOnLineChart':
        sendResponse(this.manage.getOnLineChart(data.key))
        break
      case 'getContrastChart':
        sendResponse(this.manage.getContrastChart(data.key))
        break
      case 'getGiftChart':
        sendResponse(this.manage.getGiftChart(data.key))
        break
      case 'getHistoryRoom':
        chrome.storage.sync.get(null, (items) => {
          sendResponse(items)
        })
        break
      case 'removeHistoryRoom':
        chrome.storage.sync.remove(data.key)
        sendResponse(null)
        break
    }
    return true
  }
  getDate () {
    let date = new Date()
    return date.getFullYear() + '/' + (date.getMonth() + 1) + '/' + date.getDate() + ' ' + date.getHours() + ':' + date.getMinutes()
  }
  onMessage (message) {}
}
